package com.htt.app.doctruyendemkhuya_joyfm.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.preference.PreferenceManager;

import com.htt.app.doctruyendemkhuya_joyfm.R;
import com.htt.app.doctruyendemkhuya_joyfm.config.Config;
import com.htt.app.doctruyendemkhuya_joyfm.object.Show;

public class Utils {
	
	/**
	 * Kiểm tra tồn tại kết nối internet
	 * @return
	 */
	public static boolean haveNetworkConnection(Activity ctx) {
		ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
		try {
			return cm.getActiveNetworkInfo().isConnectedOrConnecting();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static void showDialog(final Context ctx, String title,
			String message) {

		String yes = ctx.getString(android.R.string.ok);

		AlertDialog.Builder dia = new AlertDialog.Builder(ctx);
		dia.setTitle(title);
		dia.setMessage(message);
		dia.setPositiveButton(yes, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		dia.create().show();
	}

	public static void showDialog(final Context ctx, String title,
			String message, final boolean back) {

		String yes = ctx.getString(R.string.exit_app);
		String no = ctx.getString(R.string.no_exit_app);
		
		AlertDialog.Builder dia = new AlertDialog.Builder(ctx);
		dia.setTitle(title);
		dia.setMessage(message);
		dia.setPositiveButton(yes, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				 	
					dialog.dismiss();
					Activity activity = (Activity) ctx;
					activity.finish();
				
			}
		});
		dia.setNegativeButton(no, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
					dialog.dismiss();
				
			}
		});
		
		dia.create().show();
	}
	
/**
 * 	show dialog when exit app
 * @param ctx
 * @param title
 * @param message
 * @param back
 
	public static void showDialogExitApp(final Context ctx, String title,
			String message) {

		String yes = ctx.getString(R.string.exit_app);
		String no = ctx.getString(R.string.no_exit_app);
		String nghe_an = ctx.getString(R.string.nge_an);
		
		AlertDialog.Builder dia = new AlertDialog.Builder(ctx);
		dia.setTitle(title);
		dia.setMessage(message);
		dia.setPositiveButton(yes, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
					Clock.isFinish = true;
					dialog.dismiss();
					Activity activity = (Activity) ctx;
					activity.finish();
				
			}
		});
		dia.setNegativeButton(no, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
					dialog.dismiss();
				
			}
		});
		
		dia.setNeutralButton(nghe_an, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub

				dialog.dismiss();
				Activity activity = (Activity) ctx;
				activity.finish();
			}
		});
		
		dia.create().show();
	}
*/	
	
	public static int milliSecondsToHours(long milliseconds) {
		
		// Convert total duration into time
		int hours = (int)( milliseconds / (1000*60*60));
		return hours;
	}
	
	public static int milliSecondsToMinutes(long milliseconds) {
		
		int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
		return minutes;
	
	}
	
	/**
	 * Function to convert milliseconds time to
	 * Timer Format
	 * Hours:Minutes:Seconds
	 * */
	public static String milliSecondsToTimer(long milliseconds){
		String finalTimerString = "";
		String secondsString = "";
		
		// Convert total duration into time
		   int hours = (int)( milliseconds / (1000*60*60));
		   int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
		   int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
		   // Add hours if there
		   if(hours > 0){
			   finalTimerString = hours + ":";
		   }
		   
		   // Prepending 0 to seconds if it is one digit
		   if(seconds < 10){ 
			   secondsString = "0" + seconds;
		   } else {
			   secondsString = "" + seconds;}
		   
		   finalTimerString = finalTimerString + minutes + ":" + secondsString;
		
		// return timer string
		return finalTimerString;
	}
	
	/**
	 * Function to get Progress percentage
	 * @param currentDuration
	 * @param totalDuration
	 * */
	public static int getProgressPercentage(long currentDuration, long totalDuration){
		Double percentage = (double) 0;
		
		long currentSeconds = (int) (currentDuration / 1000);
		long totalSeconds = (int) (totalDuration / 1000);
		
		// calculating percentage
		percentage =(((double)currentSeconds)/totalSeconds)*100;
		
		// return percentage
		return percentage.intValue();
	}

	/**
	 * Function to change progress to timer
	 * @param progress - 
	 * @param totalDuration
	 * returns current duration in milliseconds
	 * */
	public static int progressToTimer(int progress, int totalDuration) {
		int currentDuration = 0;
		totalDuration = (int) (totalDuration / 1000);
		currentDuration = (int) ((((double)progress) / 100) * totalDuration);
		
		// return current duration in milliseconds
		return currentDuration * 1000;
	}

	/**
	 *  Fuction to check exist of table Categories in sqlite
	 * @param ctx
	 * @return true if table Categories exist
	 */
	public static boolean checkExistCategories(Context ctx) {
		return PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean(Config.SHARE_CATEGORIES, false);
	}
	
	/**
	 * Function to check exist of table CategoryType in sqlite 
	 * @return true if table CategoryType exist
	 */
	public static boolean checkExistCategoryType(Context ctx) {
		return PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean(Config.SHARE_CATEGORYTYPE, false);
	}
	
	/**
	 * Function to check exist of table Channel in sqlite
	 * @param ctx
	 * @return true if table Channel exist
	 */
	public static boolean checkExistChannel(Context ctx) {
		return PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean(Config.SHARE_CHANNEL, false);
	}
	
	public static boolean checkExistImage(Context ctx) {
		return PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean(Config.SHARE_IMAGE, false);
	}
	
	public static int getIndexShow(Show show, List<Show> listShow) {
		int index = 0;
		for(int i = 0; i < listShow.size(); i++) {
			if(show.getId() == listShow.get(i).getId()) {
				index = i;
				break;
			}
		}
		return index;
	}
	
	// convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
    	if(bitmap == null)
    		return null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }
 
    // convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
    	if(image == null)
    		return null;
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
    
    /**
     * get bitmap from url
     */
    public static Bitmap loadBitmap(String url) {
        Bitmap bitmap = null;
        try {
        	URL u = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) u.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(input);
//            InputStream in = new java.net.URL(url).openStream();
//            bitmap = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    
	/*
	 * radom choose image when no image
	 */
	private static int bg_media[] = {R.drawable.icon1,
			R.drawable.icon2, R.drawable.icon3, 
			R.drawable.icon4, R.drawable.icon5, 
			R.drawable.icon6, R.drawable.icon7,
			R.drawable.icon8, R.drawable.icon9,
			R.drawable.icon10, R.drawable.icon11,
			R.drawable.icon12, R.drawable.icon13,
			R.drawable.icon14, R.drawable.icon15,
			R.drawable.icon16, R.drawable.icon17,
			R.drawable.icon18, R.drawable.icon19,
			R.drawable.icon20, R.drawable.icon21,
			R.drawable.icon22 };
	public static int getImageRadom() {
		Random random = new Random();
		int select = random.nextInt(bg_media.length);
		return bg_media[select];
	}
	
}
